package pri.zxx.webdemo;

import com.itextpdf.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import org.springframework.core.io.ClassPathResource;

import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class ItextWordTest {

    protected static BaseFont FSChinese;

    static {
        try {
            FSChinese = BaseFont.createFont(new ClassPathResource("files/仿宋_GB2312.ttf").getPath(), BaseFont.IDENTITY_H, com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            throw new RuntimeException("加载自定义字体异常");
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException, DocumentException, com.itextpdf.text.DocumentException {
        Path path = Paths.get("test.doc");
        OutputStream outputStream;
        try {
            Files.deleteIfExists(path);
            outputStream = Files.newOutputStream(path);
        } catch (IOException e) {
            throw new RuntimeException("生成临时文件异常：" + path);
        }

        Document document = new Document(PageSize.A4, 90, 90, 72, 72);
        RtfWriter2 writer = RtfWriter2.getInstance(document, outputStream);
        document.open();

        Font font7 = new Font(FSChinese, 12, Font.NORMAL);
        Font font6 = new Font(FSChinese, 9, Font.NORMAL);

        // HeaderFooter的第2个参数为false时代表不打印页码
        //页眉如果设置两次 第一次内容将被替换，所以只能设置一次通过“\n”换行，这样做的缺点就是不能设置两种字体
        HeaderFooter header = new HeaderFooter(new Phrase("新希望饲料研究院研发报告123", font6), false);  //页脚设置页码
//        document.addHeader("新希望饲料研究院研发报告123", "");
        document.setHeader(header);
        HeaderFooter footer = new HeaderFooter(new Phrase("-", font6), new Phrase("-", font6));  //页脚设置页码
        // 0是靠左  1是居中 2是居右
        footer.setAlignment(1);
        document.setFooter(footer);
        // 页眉页脚的设置一定要在open前设置好

        //itext-asian 不和itext版本匹配将报不识别字体的错
//        BaseFont bfChinese = BaseFont.createFont("仿宋","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        Font font = new Font(FSChinese, 12, Font.NORMAL); //1
        Font font3 = new Font(FSChinese, 12, Font.NORMAL);//一
        Font font10 = new Font(FSChinese, 12, Font.BOLD);//一
        Font font16 = new Font(FSChinese, 16, Font.BOLD);//一
        Font font2 = new Font(FSChinese, 21, Font.BOLD);//大标题
        Font font4 = new Font(FSChinese, 12, Font.BOLD);//1.1 正文

        Paragraph p1 = new Paragraph("不同水平添加剂在肉鸡上的应用评估", font16);
        p1.setSpacingAfter(12);
        p1.setSpacingBefore(12);
        p1.setAlignment(Element.ALIGN_CENTER);
        document.add(p1);

        Phrase phrase = new Phrase("    摘 要: ");
        phrase.setFont(font10);
        phrase.setLeading(25f);
        document.add(phrase);

        Paragraph phrase2 = new Paragraph("本试验旨在研究不同水平添加剂对肉鸡生长性能、屠宰性能和肠道评分的影响。试验选取1日龄罗斯308商品肉仔鸡公雏1500只，分为5个处理，每个处理10个重复，每个重复30只。①生长性能结果表明，不同添加剂水平对肉鸡26-37日龄和1-37日龄各生长性能指标均无显著影响（P > 0.05）。②屠宰性能结果表明，不同水平添加剂对肉鸡各屠宰性能指标均无显著影响（P > 0.05）。③肠道评分结果表明，不同添加剂水平对粘液、黏膜脱落、后肠段含料量指标有一定影响，随着不同添加剂水平的降低，肠道评分有降低-升高-降低的趋势。终上所述，本试验条件下，不同水平添加剂对肉鸡生长性能、屠宰性能均无显著影响，随着添加剂水平的降低，肠道健康有所改善。 ");
        phrase2.setFont(font3);
        phrase2.setSpacingAfter(0);
        phrase2.setSpacingBefore(0);
        phrase2.setLeading(25f);
        phrase2.setAlignment(Element.ALIGN_JUSTIFIED);
        document.add(phrase2);


        Paragraph p3 = new Paragraph("1.  售后服务保障", font4);
        p3.setSpacingAfter(100);
        p3.setSpacingBefore(100);
        p3.setAlignment(1);
        document.add(p3);


        Paragraph p4 = new Paragraph("想要展示的段落。。。", font);
        p1.setSpacingAfter(10);
        p1.setSpacingBefore(10);
        p1.setAlignment(1);
        document.add(p4);
        Table t = new Table(1);
        t.setWidth(100);
        t.setBorder(Rectangle.TOP+Rectangle.BOTTOM);
        t.setBorderWidth(1.5f);

        Color borderColor = new Color(0, 102, 0);
        Font font9 = new Font(FSChinese, 9, Font.NORMAL); //1
        Table t1 = new Table(8);
        t1.setPadding(8f);
        t1.setWidth(100);
        t1.setBorder(Rectangle.TOP);
        t1.setBorderWidth(1.5f);
        t1.setBorderColor(borderColor);
        t1.setCellsFitPage(true);

        List<String> title1 = Arrays.asList("26d", "26-37d", "37d");
        List<String> title2 = Arrays.asList("BW(g)", "ADG(g/d)", "FCR", "ADFI(g/d)", "育肥指数", "成活率(%)", "BW(g)");

        Cell cell = new Cell(new Chunk("处理", font9));
        cell.setColspan(1);
        cell.setRowspan(2);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_CENTER);

        cell.setBorderColor(borderColor);
        cell.setBorderWidth(1.5f);
        cell.setBorder(Rectangle.TOP);

        t1.addCell(cell);
        title1.forEach(s -> {
            Cell c = new Cell();
            c.add(new Chunk(s, font9));
            c.setHorizontalAlignment(Element.ALIGN_CENTER);
            c.setUseBorderPadding(true);
            c.setBorder(Rectangle.TOP);
            c.setBorderColor(borderColor);
            c.setBorderWidth(1.5f);
            if (s.equals("26-37d")) {
                c.setColspan(5);
            } else {
                c.setColspan(1);
            }
            t1.addCell(c);
        });
        title2.forEach(s -> {
            Cell c = new Cell();
            c.add(new Chunk(s, font9));
            c.setHorizontalAlignment(Element.ALIGN_CENTER);
            c.setVerticalAlignment(Element.ALIGN_CENTER);

            c.setBorderColor(borderColor);
            c.setBorderWidth(1f);
            c.setBorder(Rectangle.TOP+Rectangle.BOTTOM);

            c.setColspan(1);
            t1.addCell(c);
        });

        for (int i = 0; i < 8; i++) {
            Cell c = new Cell();
            c.add(new Chunk(i + "1ccc", font9));
            c.setHorizontalAlignment(Element.ALIGN_CENTER);
            c.setVerticalAlignment(Element.ALIGN_CENTER);
//
            c.setBorderColor(borderColor);
            c.setBorder(Rectangle.BOTTOM+Rectangle.TOP);
            c.setBorderWidth(1f);
            c.setColspan(1);
            t1.addCell(c);
        }

        for (int i = 0; i < 8; i++) {
            Cell c = new Cell();
            c.add(new Chunk(i + "ccc", font9));
            c.setHorizontalAlignment(Element.ALIGN_CENTER);
            c.setVerticalAlignment(Element.ALIGN_CENTER);
//
            c.setBorderColor(borderColor);
            c.setBorder(Rectangle.BOTTOM);
            c.setBorderWidth(1.5f);
            c.setColspan(1);
            t1.addCell(c);
        }

        document.add(t1);

        String text2 = "";

//若text2内容为页面存储到数据库中的段落文字，当debug模式查询数据库时可见换行符为“\r\n”,

//　　因此换行后还会有一行空行，将\r替换为“空字符串”，只留\n即可去除空行。eg:text2.replaceAll("\r", "")
        Paragraph p5 = new Paragraph(text2, font);
        p1.setSpacingAfter(10);
        p1.setSpacingBefore(10);
        p1.setAlignment(1);
        document.add(p5);

        document.close();
    }
}
